package wwk.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.util.EncodingUtils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;



public class FileUtil
{
	private static final String TAG="FileUtil";
	public static String FilesDir="";
	
	public static void setFilesDir(Context context)
	{
		FilesDir=context.getFilesDir().getAbsolutePath();
	}
	
	public static String getFilePathNameInFilesDir(String fileName)
	{
		return FilesDir+File.separator+fileName;
	}
	
	//���� /mnt/sdcard
	public static String getSdCardDir()
	{
		boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);   //�ж�sd���Ƿ���� 
	    if(sdCardExist)   
	    {                               
	    	File sdDir = Environment.getExternalStorageDirectory();//��ȡ��Ŀ¼ 
	    	 return sdDir.toString(); 
	    }   

	    return null;
	}
	
	static public boolean isSdCardExists()
	{
		boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);   //�ж�sd���Ƿ���� 
	    return sdCardExist;
	}
	
	public static boolean isPathWritable(String path)
	{
		boolean write=true;
		
		File file=new File(path);
		if (! file.exists()) {
            //msg = "Parent directory of file does not exist";
            write=false;
        } else if (! file.isDirectory()) {
           // msg = "Parent of file is not a directory";
            write=false;
        } else if (! file.canWrite()) {
           // msg = "Parent directory of file is not writable";
            write=false;
        }
		
		return write;
	}
	
	public static boolean createFile(String filePathName)
	{
		File file=new File(filePathName);
		return createFile(file);
	}
	
	public static boolean createPath(String path)
	{
		 File newdir = new File(path);
		 boolean ret=newdir.mkdirs();
		 
		 return ret;
	}
	
	public static boolean createFile(File file)
	{
		boolean ret=false;
		if(!file.exists())
    	{
			//����һ��Ŀ¼
			String absolutePath=file.getAbsolutePath();
		    int pos =absolutePath.lastIndexOf('\\');
		    if(pos<0)
		    {
		    	pos =absolutePath.lastIndexOf('/');
		    }
		    if ( pos >=0 )
		    {
			    String dirname = absolutePath.substring(0,pos); 
			    File newdir = new File(dirname);
			    newdir.mkdir();
		    }
			   
    		try
			{
				file.createNewFile();
				ret=true;
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
    	}
		return ret;
	}
	
	/**
	 * ɾ��һ��Ŀ¼���ļ�
	 * @param filePathName
	 */
	public static boolean rename(String filePathName,String newFileName)
	{
		File file=new File(filePathName);
		String newFilePathName=file.getAbsolutePath()+newFileName;
		File newFile=new File(newFilePathName);
		boolean ret=file.renameTo(newFile);
		return ret;
	}
	
	/**
	 * ɾ��һ��Ŀ¼���ļ�
	 * @param filePathName
	 */
	public static void delete(String filePathName)
	{
		if(filePathName==null || filePathName.length()==0)
		{
			return;
		}
		
		File file=new File(filePathName);
		delete(file);
	}
	
	/**
	 * ɾ��һ��Ŀ¼���ļ�
	 * @param file
	 */
	public static void delete(File file)
	{ 
	   if(file.exists())
	   { 
		    if(file.isFile())
		    { 
		    	file.delete(); 
		    }
		    else if(file.isDirectory())
		    { 
			     File files[] = file.listFiles(); 
			     for(int i=0;i<files.length;i++)
			     { 
			    	 delete(files[i]); 
			     } 
				 file.delete(); 
		    } 
	   }
	} 

	
	public static boolean isFileExists(String filePathName)
	{
		File file=new File(filePathName);
		boolean exists=false;
		if(file.isFile())
			exists=file.exists();
    	return exists;
	}
	
	public static long write(String filePathName,byte[] bytes,int bytesSize,boolean append)
	{		
	    	File file=new File(filePathName);
	    return FileUtil.	write(file,bytes,bytesSize,append);
	}

	public static long write(File file,byte[] bytes,int bytesSize,boolean append)
	{
		long writesize=-1;
		
		if(bytes==null)
			return -1;
		
		if(bytesSize>bytes.length || bytesSize<0)
		{
			bytesSize=bytes.length;
		}
     	  		
	    	try
	    	{
	    		if(!file.exists())
	        	{
	    			createFile(file);
	        	}
	    		
	  	  		OutputStream out=new FileOutputStream(file,append);
	  	  		out.write(bytes,0,bytesSize);
	  	  		out.close();	
	  	  		writesize=bytesSize;
	    	}
	    	catch(IOException e)
	    	{
	    		writesize=-1;
	    		Log.e(TAG,e.getMessage().toString());
	    	}
	    	
	    	return writesize;
	}
	
	public static long getFileLength(String filePathName)
	{
		File file=new File(filePathName);
		long length=file.length();
		return length;
	}
	
	public static byte[] read(String filePathName)
	{
		byte[] bytes=read(filePathName,0,-1);
		return bytes;
	}
	
	public static byte[] read(File file)
	{
		byte[] bytes=read(file,0,-1);
		return bytes;
	}
	
	public static byte[] read(String filePathName,int pos,int size)
	{
		File file=new File(filePathName);
		return FileUtil.read(file, pos, size);
	}
	
	public static byte[] read(File file,int pos,int size)
	{
		byte[] bytes=null;
		
		if(file.exists())
		{
			try
			{
				if(pos<0)
				{
					pos=0;
				}
				
				InputStream input=new FileInputStream(file);
				int available=input.available();
				if(size<=0)
				{
					size=available-pos;
				}
				if(pos<available)
				{
					//����ݿɶ�
					if(available<pos+size)
					{
						size=available-pos;
					}

					bytes=new byte[size];
					input.read(bytes,pos,size);
				}
				
				input.close();
			}
			catch (FileNotFoundException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				bytes=null;
				e.printStackTrace();
			}
		}
		
		return bytes;
	}
	
	public static byte[] read(int resId,Context context )
	{
		InputStream inputStream = context.getResources().openRawResource(resId);//R.raw.
		byte[] bytes=StreamUtil.readStream(inputStream);
		
		return bytes;
	}
	
	public static InputStream getInputStream(String filePathName)
	{
		File file=new File(filePathName);
		return getInputStream(file);
	}
	
	public static InputStream getInputStream(File file)
	{
		if(file.exists())
		{
			try
			{
				InputStream input=new FileInputStream(file);
				return input;
			}
			catch (FileNotFoundException e)
			{
				e.printStackTrace();
			}
		}
		
		return null;
	}
	
	//InputStream.read����ʼָ��ָ��offset+length
	public static byte[] read(InputStream inputStream,int size)
	{
		byte[] bytes=null;
		
		int readedSize=0;
		try
		{
			int available=inputStream.available();
			if(size<=0 || size>available)
			{
				size=available;
			}
			
			if(size>0)
			{
				bytes=new byte[size];

				while(readedSize<size)
				{
					readedSize=inputStream.read(bytes,readedSize,size-readedSize)+readedSize;
				}
			}
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			bytes=null;
			e.printStackTrace();
		}
		
		return bytes;
	}
	
	static public String getStringFromAssets(Context context,String fileName,String encoding)
	{
	    String result = "";
	    try 
	    {
			InputStream in = context.getResources().getAssets().open(fileName);
			int lenght = in.available();
			byte[]  buffer = new byte[lenght];
			in.read(buffer);
			result = EncodingUtils.getString(buffer,encoding);//"gb2312"
		} 
	    catch (Exception e) 
		{
			e.printStackTrace();
		}
		return result;
	}
	
	static public String getStringFromRawResource(Context context,int resourceId,String encoding)
	{
	    String result = "";
	    try 
	    {
			InputStream in = context.getResources().openRawResource(resourceId);
			int lenght = in.available();
			byte[]  buffer = new byte[lenght];
			in.read(buffer);
			result = EncodingUtils.getString(buffer,encoding);//"utf-8"
		} 
	    catch (Exception e) 
	    {
			e.printStackTrace();
		}
		return result;
	}
	
}